#include <stdio.h>
#include <stdlib.h>
#include "bitmap.h"

void load_bitmap(char *file, BITMAP *b) {
	FILE *fp;
	long index;
	word num_colors;
	int x;

	/* open the file */
	if ((fp = fopen(file,"rb")) == NULL)
	{
		printf("Error opening file %s.\n",file);
		exit(1);
	}

	/* check to see if it is a valid bitmap file */
	if (fgetc(fp)!='B' || fgetc(fp)!='M')
	{
		fclose(fp);
		printf("%s is not a bitmap file.\n",file);
		exit(1);
	}

	/* read in the width and height of the image, and the
	 number of colors used; ignore the rest */
	fskip(fp,16);
	fread(&b->width, sizeof(word), 1, fp);
	fskip(fp,2);
	fread(&b->height,sizeof(word), 1, fp);
	fskip(fp,22);
	fread(&num_colors,sizeof(word), 1, fp);
	fskip(fp,6);

	/* assume we are working with an 8-bit file */
	if (num_colors==0) num_colors=256;


	/* try to allocate memory */
	if ((b->data = (byte *) malloc((word)(b->width*b->height))) == NULL)
	{
		fclose(fp);
		printf("Error allocating memory for file %s.\n",file);
		exit(1);
	}

	/* Ignore the palette information for now.
	 See palette.c for code to read the palette info. */
	fskip(fp,num_colors*4);

	/* read the bitmap */
	for(index=(b->height-1)*b->width;index>=0;index-=b->width)
	for(x=0;x<b->width;x++)
		b->data[(word)index+x]=(byte)fgetc(fp);

	fclose(fp);
}